package cn.wikiflyer.beikang.payali;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import cn.wikiflyer.beikang.IApplication;

import com.alipay.sdk.app.PayTask;

/**
 * 支付
 */
public class PaymentObject implements IPay {

	private static PaymentObject instance = null;
	private OnPayListener mListener;
	private Activity activity;

	private String orderno;
	private String sign;
	private String orderInfo;

	public PaymentObject(Activity activity) {
		super();
		this.activity = activity;
	}

	public static PaymentObject getInstance(Activity activity) {
		if (instance == null) {
			instance = new PaymentObject(activity);
		}
		return instance;
	}

	/**
	 * 设置支付回调
	 */
	public void setOnPayListener(OnPayListener mOnPayListener) {
		this.mListener = mOnPayListener;
	}
	public void setOrderno(String orderno) {
		this.orderno = orderno;
	}
	@Override
	public String getOrderInfo(String subject, String body, String price) {
		// 合作者身份ID
		orderInfo = "partner=" + "\"" + PARTNER + "\"";
		// 卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";
		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + orderno + "\"";
		// 商品名称
		orderInfo += "&subject=" + "\"订单编号:" + orderno + ",交易金额" + price + "元"
				+ "\"";
		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";
		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";
		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + IApplication.BASE_URL + Notify_url
				+ "\"";
		// 接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";
		// 支付类型， 固定值
		orderInfo += "&payment_type=\"2\"";
		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";
		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";
		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";
		// 调用银行卡支付，需配置此参数，参与签名， 固定值
		// orderInfo += "&paymethod=\"expressGateway\"";
		return orderInfo;
	}
	/**
	 * 支付要传入的参数
	 */
	private String payInfo() {
		String sign = sign(orderInfo);
		Log.e("wj", "sign : " + sign);
		try {
			// 仅需对sign 做URL编码
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();
		return payInfo;
	}

	public String getSignType() {
		return "sign_type=\"RSA\"";
	}

	@Override
	public void Pay() {
		Runnable payRunnable = new Runnable() {
			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(activity);
				// 调用支付接口
				String result = alipay.pay(payInfo());
				Log.e("wj", "result : " + result);
				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				Result resultObj = new Result((String) msg.obj);
				String resultStatus = resultObj.resultStatus;
				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(activity, "支付成功", Toast.LENGTH_SHORT).show();
					mListener.success();
				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000”
					// 代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(activity, "支付结果确认中", Toast.LENGTH_SHORT)
								.show();
					} else {
						Toast.makeText(activity, "支付失败", Toast.LENGTH_SHORT)
								.show();
					}
					mListener.failed();
				}
				break;
			}
			case SDK_CHECK_FLAG: {
				Toast.makeText(activity, "检查结果为：" + msg.obj, Toast.LENGTH_SHORT)
						.show();
				break;
			}
			default:
				break;
			}
		};
	};

	/**
	 * 支付结果监听
	 */
	public interface OnPayListener {
		public void success();

		public void failed();
	}

	@Override
	public String sign(String content) {
		return SignUtils.sign(content, RSA_PRIVATE);
	}

}
